// 使用mock 模拟定义接口
import Mock from "mockjs";
let List = []; // 返回的数据,相当于后台数据库
for (let i = 0; i < 100; i++) {
  List.push({
    id: i,
    name: Mock.Random.cname(), // 随机生成中文名
    age: Mock.Random.integer(18, 25), // 随机生成数字
    major: "html5",
    address: Mock.Random.county(true),
    pay: Mock.Random.integer(0, 1),
    graduateTime: Mock.Random.date("yyyy-MM-dd"),
  });
}

// console.log(List);

export default {
  // 获取所有的用户接口
  userMock: (options) => {
    let { searchValue, page, size } = JSON.parse(options.body); // 获取参数
    // console.log(searchValue, page, size);
    // 第一步: 根据search返回对应的数据
    let newlist = List.filter((item) => {
      return item.name.indexOf(searchValue) != -1;
    });
    // console.log(newlist);

    // 第二步: 根据page 和 size 返回对应的最终数据
    // 将newList的前十条数据返回  arr.slice(起始下标,结束下标)
    // 1  0-10      (1-1)*10 - 1*10  => ((page-1)*size,page*size)
    // 2  10-20     (2-1)*10 - 2*10
    // 3  20-30     (3-1)*10 - 3*10
    let newlist1 = newlist.slice((page - 1) * size, page * size);

    return {
      code: 200,
      msg: "请求成功",
      data: newlist1,
      totalpage: List.length, // 数据总条数
      size: size,
      currentPage: page,
    };
  },

  // 删除用户接口
  deleteMock: (options) => {
    // console.log(options);
    // 获取参数
    let id = options.url.split("?")[1].split("=")[1];
    // console.log(id);
    let list1 = List.filter((item) => {
      return item.id != id;
    });

    List = list1;
    return {
      code: 200,
      msg: "删除成功",
      data: null,
    };
  },

  // 编辑用户接口
  editMock: (options) => {
    // console.log(JSON.parse(options.body));
    let { address, age, graduateTime, id, major, name, pay } = JSON.parse(
      options.body
    );
    List.forEach((item) => {
      if (item.id == id) {
        item.age = age;
        item.graduateTime = graduateTime;
        item.major = major;
        item.name = name;
        item.pay = pay;
        item.address = address;
      }
    });
    return {
      code: 200,
      msg: "编辑成功",
      data: null,
    };
  },
  // 添加用户接口
  addMock: (options) => {
    let { address, age, graduateTime, major, name, pay } = JSON.parse(
      options.body
    );
    List.unshift({
      id: List[0].id - 1,
      address,
      age,
      graduateTime,
      major,
      name,
      pay,
    });
    return {
      code: 200,
      msg: "添加成功",
      data: null,
    };
  },
};
